package edu.software.PBL_Management_System.demand.service;

import edu.software.PBL_Management_System.demand.repository.DemandRepository;
import edu.software.PBL_Management_System.entity.Demand;
import edu.software.PBL_Management_System.entity.User;
import jakarta.annotation.Resource;
import jakarta.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;

@Service
public class DemandService {

    //依赖注入
    @Resource
    private DemandRepository demandRepository;

    /// 创造和更新需求
    @Transactional
    public Demand createDemand(Demand demand) {
        // 设置初始状态为草稿
        demand.setStatus(Demand.DemandStatus.DRAFT);
        return demandRepository.save(demand);
    }

    //更新需求
    @Transactional
    public Demand updateDemand(Demand demand) {
        Demand existingDemand = getDemandById(demand.getId());

        if (demand.getTitle() != null) {
            existingDemand.setTitle(demand.getTitle());
        }
        if (demand.getDescription() != null) {
            existingDemand.setDescription(demand.getDescription());
        }
        if (demand.getMindMapData() != null) {
            existingDemand.setMindMapData(demand.getMindMapData());
        }
        if (demand.getStatus() != null) {
            existingDemand.setStatus(demand.getStatus());
        }
        if (demand.getTags() != null) {
            existingDemand.setTags(demand.getTags());
        }

        return demandRepository.save(existingDemand);
    }

    /// 查询操作
    //按id查找需求
    public Demand getDemandById(Long id) {
        return demandRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Demand not found"));
    }

    //按创作者查找需求
    public List<Demand> getDemandsByCreator(User creator) {
        return demandRepository.findByCreator(creator);
    }
    //分页按创作者查找
    public Page<Demand> getDemandsByCreator(User creator, Pageable pageable) {
        return demandRepository.findByCreator(creator, pageable);
    }

    //查询需求状态
    public List<Demand> getDemandsByStatus(Demand.DemandStatus status) {
        return demandRepository.findByStatus(status);
    }

    //查询上一级需求
    public List<Demand> getSubDemands(Long parentId) {
        return demandRepository.findByParentId(parentId);
    }

    //查询最顶层需求
    public List<Demand> getMainDemands() {
        return demandRepository.findByParentIdIsNull();
    }

    //分页查询最顶层需求（支持过滤当前用户）
    public Page<Demand> getMainDemands(Pageable pageable, Long excludeUserId) {
        if (excludeUserId != null) {
            return demandRepository.findByParentIdIsNullAndCreatorIdNot(excludeUserId, pageable);
        }
        return demandRepository.findByParentIdIsNull(pageable);
    }

    //按标题查询需求
    public List<Demand> searchDemandsByTitle(String title) {
        return demandRepository.findByTitleContaining(title);
    }

    ///删除需求
    @Transactional
    public void deleteDemand(Long id) {
        Demand demand = getDemandById(id);
        // 如果是主需求，需要先删除所有子需求
        if (demand.getParentId() == null) {
            List<Demand> subDemands = getSubDemands(id);
            demandRepository.deleteAll(subDemands);
        }
        demandRepository.delete(demand);
    }

    ///状态管理
    @Transactional
    public Demand publishDemand(Long id) {
        Demand demand = getDemandById(id);
        demand.setStatus(Demand.DemandStatus.PUBLISHED);
        return demandRepository.save(demand);
    }
    //更新需求状态
    @Transactional
    public Demand updateDemandStatus(Long id, Demand.DemandStatus status) {
        Demand demand = getDemandById(id);
        demand.setStatus(status);
        return demandRepository.save(demand);
    }

    //？
    public List<Demand> getDemandsByCreatorAndStatus(User creator, Demand.DemandStatus status) {
        return demandRepository.findByCreatorAndStatus(creator, status);
    }

    /// 获取需求
    /**
     * 获取需求的详细信息
     * @param id 需求ID
     * @return 包含需求详细信息的Map
     */
    public Map<String, Object> getDemandDetailsById(Long id) {
        return demandRepository.findDetailedInfoById(id);
    }

    /**
     * 获取用户需求的基本信息列表
     * @param creator 创建者
     * @return 需求基本信息列表
     */
    public List<Map<String, Object>> getDemandBasicListByCreator(User creator) {
        return demandRepository.findBasicInfoByCreator(creator);
    }

    /**
     * 获取用户的顶级需求基本信息列表
     * @param creator 创建者
     * @return 顶级需求基本信息列表
     */
    public List<Map<String, Object>> getTopLevelDemandBasicListByCreator(User creator) {
        return demandRepository.findTopLevelBasicInfoByCreator(creator);
    }

    /**
     * 获取用户特定状态需求的基本信息列表
     * @param creator 创建者
     * @param status 需求状态
     * @return 需求基本信息列表
     */
    public List<Map<String, Object>> getDemandBasicListByCreatorAndStatus(User creator, Demand.DemandStatus status) {
        return demandRepository.findBasicInfoByCreatorAndStatus(creator, status);
    }

    /**
     * 创建空的子需求
     * @param parentId 父需求ID
     * @param creator 创建者
     * @return 包含需求详细信息的Map
     */
    @Transactional
    public Map<String, Object> createEmptySubDemand(Long parentId, User creator) {
        // 验证父需求是否存在
        Demand parentDemand = getDemandById(parentId);

        // 创建空的子需求
        Demand subDemand = new Demand();
        subDemand.setTitle("新建子需求");
        subDemand.setDescription("");
        subDemand.setMindMapData("");
        subDemand.setStatus(Demand.DemandStatus.DRAFT);
        subDemand.setParentId(parentId);
        subDemand.setCreator(creator);

        // 保存子需求
        Demand savedDemand = demandRepository.save(subDemand);

        // 返回详细信息
        return demandRepository.findDetailedInfoById(savedDemand.getId());
    }


    /**
     * 获取所有已评论的需求列表
     */
    public List<Demand> getCommentedDemands() {
        return demandRepository.findAllCommentedDemands();
    }

    public Map<String, Object> getDemandMindmapData(Long id) {
        return demandRepository.findMindmapDataById(id);
    }
}
